package com.newsanalysis.controller;

import com.newsanalysis.crawler.NewsCrawlerManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * 爬虫管理控制器
 */
@Slf4j
@Controller
@RequestMapping("/admin/crawler")
@RequiredArgsConstructor
public class CrawlerController {
    
    private final NewsCrawlerManager crawlerManager;
    
    // 爬虫运行状态（实际应用中应该从持久化配置或服务状态中获取）
    private boolean isRunning = false;
    
    /**
     * 显示爬虫管理页面
     */
    @GetMapping
    public String showCrawlerManagement(Model model) {
        model.addAttribute("isRunning", isRunning);
        return "admin/crawler";
    }
    
    /**
     * 启动定时爬虫
     */
    @PostMapping("/start")
    public String startCrawler(Model model) {
        if (!isRunning) {
            try {
                // 实际启动定时任务的逻辑
                isRunning = true;
                
                model.addAttribute("message", "定时爬虫任务已启动");
                log.info("定时爬虫任务已启动");
            } catch (Exception e) {
                model.addAttribute("error", "启动爬虫失败: " + e.getMessage());
                log.error("启动爬虫失败", e);
            }
        } else {
            model.addAttribute("message", "定时爬虫任务已在运行中");
        }
        
        model.addAttribute("isRunning", isRunning);
        return "admin/crawler";
    }
    
    /**
     * 停止定时爬虫
     */
    @PostMapping("/stop")
    public String stopCrawler(Model model) {
        if (isRunning) {
            try {
                // 实际停止定时任务的逻辑
                isRunning = false;
                
                model.addAttribute("message", "定时爬虫任务已停止");
                log.info("定时爬虫任务已停止");
            } catch (Exception e) {
                model.addAttribute("error", "停止爬虫失败: " + e.getMessage());
                log.error("停止爬虫失败", e);
            }
        } else {
            model.addAttribute("message", "定时爬虫任务未在运行");
        }
        
        model.addAttribute("isRunning", isRunning);
        return "admin/crawler";
    }
    
    /**
     * 爬取所有网站
     */
    @PostMapping("/crawl-all")
    public String crawlAllSites(Model model) {
        try {
            // 创建新线程执行爬虫任务，避免阻塞用户界面
            new Thread(() -> {
                crawlerManager.crawlNews();
            }).start();
            
            model.addAttribute("message", "手动爬取任务已启动，正在后台运行...");
            log.info("手动爬取所有网站任务已启动");
        } catch (Exception e) {
            model.addAttribute("error", "爬取任务启动失败: " + e.getMessage());
            log.error("爬取任务启动失败", e);
        }
        
        model.addAttribute("isRunning", isRunning);
        return "admin/crawler";
    }
    
    /**
     * 爬取特定网站
     */
    @PostMapping("/crawl-site")
    public String crawlSpecificSite(@RequestParam String siteName, Model model) {
        if (siteName == null || siteName.trim().isEmpty()) {
            model.addAttribute("error", "请选择要爬取的网站");
            model.addAttribute("isRunning", isRunning);
            return "admin/crawler";
        }
        
        try {
            // 创建新线程执行爬虫任务，避免阻塞用户界面
            new Thread(() -> {
                int count = crawlerManager.crawlNewsBySite(siteName);
                log.info("爬取 {} 完成，获取 {} 条新闻", siteName, count);
            }).start();
            
            model.addAttribute("message", "正在爬取 " + siteName + " 的新闻，后台运行中...");
            log.info("开始爬取 {} 的新闻", siteName);
        } catch (Exception e) {
            model.addAttribute("error", "爬取 " + siteName + " 失败: " + e.getMessage());
            log.error("爬取 {} 失败", siteName, e);
        }
        
        model.addAttribute("isRunning", isRunning);
        return "admin/crawler";
    }
}

